﻿using B.MES.Customer.Application.IApplication;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace B.MES.Customer.Read.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SaleController : ControllerBase
    {
        private readonly ISalesManagementApplication _salesManagementApplication;

        public SaleController(ISalesManagementApplication salesManagementApplication)
        {
            _salesManagementApplication = salesManagementApplication;
        }

        /// <summary>
        /// 销售添加
        /// </summary>
        /// <param name="sales"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public APIResult<SaleDto> AddSale(SaleDto sales)
        {
          return _salesManagementApplication.AddSale(sales);
        }
       /// <summary>
       /// 获取客户信息
       /// </summary>
       /// <returns></returns>
        [HttpGet]
        public IActionResult GetClients()
        {
            return Ok(_salesManagementApplication.GetClients());
        }
        /// <summary>
        /// 获取销售信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public IActionResult GetSalesManagement(int PageIndex, int PageSize, string? LinkMan, int? ClientId)
        {
            var result=_salesManagementApplication.GetSalesManagement(PageIndex, PageSize, LinkMan, ClientId);
            return Ok(result);
        }
        /// <summary>
        /// 销售单删除
        /// </summary>
        /// <param name="SaleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpDelete]
        public IActionResult DeleteSale(int SaleId)
        {
            return Ok(_salesManagementApplication.DeleteSale(SaleId));
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpPut]
        public IActionResult DeletesSale(List<SalesManagement> list)
        {
            return Ok(_salesManagementApplication.DeletesSale(list));
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ImportExeclSale(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest("未选择文件或文件为空");
                }
                var formfile = Request.Form.Files[0];
                var filename= formfile.FileName;
                var fileextension = Path.GetExtension(formfile.FileName);
                if (fileextension != ".xlsx" && fileextension != ".xls")
                {
                    return BadRequest("文件格式错误");
                }
                APIResult<string>aPIResult = new APIResult<string>();
                using (var steam=new MemoryStream())
                {
                    formfile.CopyTo(steam);
                    steam.Position = 0;
                    var list = steam.Query<importSale>();
                    steam.Position = 0;
                    var sales = list.Select(x => new SalesManagement
                    {
                        ClientId = x.ClientId,
                        ContactInformation = x.ContactInformation,
                        ContactNumber = x.ContactNumber,
                        DestinationOfDelivery = x.DestinationOfDelivery,
                        LinkMan = x.LinkMan,
                        Remark = x.Remark,
                        SaleId = x.SaleId,
                        SalesDate = x.SalesDate,
                        SalesOrderNumber = x.SalesOrderNumber,
                    }).ToList();
                    _salesManagementApplication.Add(sales);
                    _salesManagementApplication.SaveChanges();
                }
                aPIResult.Success(filename);
                return Ok(aPIResult);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
       public IActionResult ExportToExcel()
        {
            try
            {
                var list = _salesManagementApplication.GetAll();
                var stream=new MemoryStream();
                stream.SaveAs(list);
                stream.Seek(0, SeekOrigin.Begin);
                return new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 
                {
                    FileDownloadName="销售列表"
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 销售反填
        /// </summary>
        /// <param name="SaleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]

        public IActionResult GetSaleInfo(int SaleId)
        {
           var result= _salesManagementApplication.GetSaleInfo(SaleId);
           return Ok(result);
        }
        /// <summary>
        /// 销售修改
        /// </summary>
        /// <param name="sales"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpPut]
        public IActionResult UpdateSale(SalesManagement sales)
        {
            var result=_salesManagementApplication.UpdateSale(sales);
            return Ok(result);
        }
        [HttpPost]
        public IActionResult GetImage(IFormFile file)
        {
             var p= Directory.GetCurrentDirectory() + "/wwwroot/PIC/" + file.FileName;
            using (FileStream fs = new FileStream(p, FileMode.Create)) {
                file.CopyTo(fs);
            };
            return Ok("http://localhost:5055/PIC/" + file.FileName);
        }
        /// <summary>
        /// 多文件上传
        /// </summary>
        /// <returns>返回路径的集合</returns>
        [HttpPost]
        public IActionResult UpFileNew()
        {
                //保存文件路径
                List<string> pathList = new List<string>();
                //获取的所有文件
                var imgList = Request.Form.Files;

                foreach (var img in imgList)
                {
                    //1、获取到目标的地址
                    string path = Directory.GetCurrentDirectory() + "/wwwroot/PIC/" + img.FileName;
                    //2、执行上传操作
                    using (FileStream fs = new FileStream(path, FileMode.Create))//using 自动清除文件流
                    {
                        img.CopyTo(fs);//文件复制到文件流
                    }

                    pathList.Add("http://localhost:5055/PIC/" + img.FileName);
                }
                return Ok(pathList);
            
        }
        [HttpPost]
        public IActionResult UploadImages(List<IFormFile> files)
        {
            List<string> fileUrls = new List<string>();

            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "PIC", fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    var fileUrl = "http://localhost:5055/PIC/" + file.FileName;
                    fileUrls.Add(fileUrl);
                }
            }

            return Ok(fileUrls);
        }

        /// <summary>
        /// 销售统计
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CountSale()
        {
            try
            {
                return Ok(_salesManagementApplication.CountSale());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
    }
}
